package com.zhugang.week03;

/**
 * @program algorithms
 * @description: linkedListStack:链表实现的栈， 链表头部插入，
 * @author: chanzhugang
 * @create: 2022/06/02 21:54
 */
public class LinkedListStack {

    private Node head = null;

    /**
     * 入栈：链表头部插入数据
     *
     * @param value
     */
    public void push(int value) {
        Node newNode = new Node(value, null);
        // 链表头插: new.next = head; head = new;
        // 链表尾插：tail.next = new; tail = new;
        newNode.next = head;
        head = newNode;
    }

    /**
     * 出栈：链表头部删除数据
     *
     * @return
     */
    public int pop() {
        if (head == null) {
            return -1;
        }
        int data = head.data;
        head = head.next;
        return data;
    }

    /**
     * 获取栈顶元素
     *
     * @return
     */
    public int peek() {
        if (head == null) {
            return -1;
        }
        return head.data;
    }

    public class Node {
        public int data;
        public Node next;

        public Node(int data, Node next) {
            this.data = data;
            this.next = next;
        }
    }
}